﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Entities.Tabs;
using DotNetNuke.Services.Installer.Packages;
using DotNetNuke.Services.Localization;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;

using CharityGamesOnline.Modules.Common;

namespace CharityGamesOnline.Modules.Game
{
    public partial class UsageDetails : CGOBase
    {
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            try
            {
                lblTitle.Text = Localization.GetString("Usage", LocalResourceFile) + Package.FriendlyName;
                UsageList.PagerSettings.FirstPageText = Localization.GetString("grd.PagerSettings.FirstPageText", LocalResourceFile);
                UsageList.PagerSettings.LastPageText = Localization.GetString("grd.PagerSettings.LastPageText", LocalResourceFile);
                UsageList.PagerSettings.NextPageText = Localization.GetString("grd.PagerSettings.NextPageText", LocalResourceFile);
                UsageList.PagerSettings.PreviousPageText = Localization.GetString("grd.PagerSettings.PreviousPageText", LocalResourceFile);
            }
            catch (Exception ex)
            {
                DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException(this, ex);
            }
        }
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            try
            {
                BindFilterList();
                if ((FilterUsageList.Visible))
                {
                    BindUsageList(int.Parse(FilterUsageList.SelectedValue), FilterUsageList.SelectedItem.Text);
                }
                else
                {
                    BindUsageList(PortalId, PortalController.GetCurrentPortalSettings().PortalName);
                }
            }
            catch (Exception ex)
            {
                DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException(this, ex);
            }
        }
        protected void FilterUsageList_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            try
            {
                if ((FilterUsageList.SelectedValue != null))
                {
                    UsageList.PageIndex = 0;
                    BindUsageList(int.Parse(FilterUsageList.SelectedValue), FilterUsageList.SelectedItem.Text);
                }
            }
            catch (Exception ex)
            {
                DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException(this, ex);
            }
        }
        protected void UsageList_PageIndexChanging(object sender, System.Web.UI.WebControls.GridViewPageEventArgs e)
        {
            try
            {
                UsageList.PageIndex = e.NewPageIndex;
                BindUsageList(int.Parse(FilterUsageList.SelectedValue), FilterUsageList.SelectedItem.Text);
            }
            catch (Exception ex)
            {
                DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException(this, ex);
            }
        }
        int _PackageID = Null.NullInteger;
        protected int PackageID
        {
            get
            {
                if ((_PackageID == Null.NullInteger && Request.QueryString["PackageID"] != null))
                {
                    _PackageID = Int32.Parse(Request.QueryString["PackageID"]);
                }
                return _PackageID;
            }
        }
        PackageInfo _Package = null;
        protected PackageInfo Package
        {
            get
            {
                if (_Package == null)
                {
                    if (PackageID == Null.NullInteger)
                    {
                        _Package = new PackageInfo();
                    }
                    else
                    {
                        _Package = PackageController.GetPackage(PackageID);
                    }
                }
                return _Package;
            }
        }
        private TabController _TabCtrl = null;
        protected TabController TabCtrl
        {
            get
            {
                if (_TabCtrl == null)
                {
                    _TabCtrl = new TabController();
                }
                return _TabCtrl;
            }
        }
        private IDictionary<int, PortalInfo> _Portals = null;
        protected IDictionary<int, PortalInfo> Portals
        {
            get
            {
                if (_Portals == null)
                {
                    _Portals = new Dictionary<int, PortalInfo>();
                    ArrayList items = new PortalController().GetPortals();
                    foreach (PortalInfo item in items)
                    {
                        _Portals.Add(item.PortalID, item);
                    }
                }
                return _Portals;
            }
        }
        protected bool IsSuperTab
        {
            get { return (this.ModuleContext.PortalSettings.ActiveTab.IsSuperTab); }
        }
        private string FormatPortalAliases(int PortalID, int TabId)
        {
            System.Text.StringBuilder str = new System.Text.StringBuilder();
            try
            {
                PortalAliasController objPortalAliasController = new PortalAliasController();
                ArrayList arr = objPortalAliasController.GetPortalAliasArrayByPortalID(PortalID);
                PortalAliasInfo objPortalAliasInfo;
                int i;
                for (i = 0; i <= arr.Count - 1; i++)
                {
                    objPortalAliasInfo = (PortalAliasInfo)arr[i];
                    str.Append("<a href=\"" + DotNetNuke.Common.Globals.AddHTTP(objPortalAliasInfo.HTTPAlias) + "\">" + objPortalAliasInfo.HTTPAlias + "</a>");
                }
            }
            catch (Exception exc)
            {
                DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
            }
            return str.ToString();
        }
        protected string GetFormattedLink(object dataItem)
        {
            StringBuilder returnValue = new StringBuilder();
            if ((dataItem is DotNetNuke.Entities.Tabs.TabInfo))
            {
                DotNetNuke.Entities.Tabs.TabInfo tab = (DotNetNuke.Entities.Tabs.TabInfo)dataItem;
                if ((tab != null))
                {
                    int index = 0;
                    TabCtrl.PopulateBreadCrumbs(ref tab);
                    foreach (DotNetNuke.Entities.Tabs.TabInfo t in tab.BreadCrumbs)
                    {
                        if ((index > 0))
                        {
                            returnValue.Append(" > ");
                        }
                        if ((tab.BreadCrumbs.Count - 1 == index))
                        {
                            string url;
                            PortalAliasController objPortalAliasController = new PortalAliasController();
                            ArrayList arr = objPortalAliasController.GetPortalAliasArrayByPortalID(t.PortalID);
                            PortalAliasInfo objPortalAliasInfo = (PortalAliasInfo)arr[0];
                            url = DotNetNuke.Common.Globals.AddHTTP(objPortalAliasInfo.HTTPAlias) + "/Default.aspx?tabId=" + t.TabID;
                            returnValue.AppendFormat("<a href=\"{0}\">{1}</a>", url, t.LocalizedTabName);
                        }
                        else
                        {
                            returnValue.AppendFormat("{0}", t.LocalizedTabName);
                        }
                        index = index + 1;
                    }
                }
            }
            return returnValue.ToString();
        }
        private void BindFilterList()
        {
            if ((PackageID != Null.NullInteger && Package != null && Package.PackageType.ToUpper() == "MODULE"))
            {
                tblFilterUsage.Visible = IsSuperTab;
                if (!IsPostBack)
                {
                    if ((FilterUsageList.Visible))
                    {
                        FilterUsageList.DataSource = Portals.Values;
                        FilterUsageList.DataTextField = "PortalName";
                        FilterUsageList.DataValueField = "PortalID";
                        FilterUsageList.DataBind();
                        FilterUsageList.Items.Insert(0, new ListItem(Localization.GetString("FilterOptionHost", LocalResourceFile), Null.NullInteger.ToString()));
                        FilterUsageList.Items.Insert(0, new ListItem(Localization.GetString("FilterOptionSelect", LocalResourceFile), "-2"));
                        FilterUsageList.Items[0].Selected = true;
                    }
                }
            }
        }
        private bool _IsListBound = false;
        private void BindUsageList(int selectedPortalID, string selectedPortalName)
        {
            if ((_IsListBound))
            {
                return;
            }
            _IsListBound = true;
            IDictionary<int, DotNetNuke.Entities.Tabs.TabInfo> tabs = null;
            string portalName = string.Empty;
            if (PackageID != Null.NullInteger && Package != null)
            {
                if (IsSuperTab)
                {
                    if (selectedPortalID == -2)
                    {
                        portalName = string.Empty;
                    }
                    else
                    {
                        tabs = BuildData(selectedPortalID);
                        portalName = selectedPortalName;
                    }
                }
                else
                {
                    tabs = BuildData(PortalId);
                    portalName = string.Empty;
                }
            }
            if ((tabs != null && tabs.Count > 0))
            {
                UsageList.Visible = true;
                UsageList.DataSource = tabs.Values;
                UsageList.DataBind();
                UsageListMsg.Text = string.Format(Localization.GetString("Msg.InUseBy", LocalResourceFile), tabs.Count.ToString(), portalName);
            }
            else if ((portalName != string.Empty))
            {
                UsageList.Visible = false;
                UsageListMsg.Text = string.Format(Localization.GetString("Msg.NotUsedBy", LocalResourceFile), portalName);
            }
            else
            {
                UsageList.Visible = false;
                UsageListMsg.Text = string.Empty;
            }
        }
        private IDictionary<int, DotNetNuke.Entities.Tabs.TabInfo> BuildData(int portalID)
        {
            IDictionary<int, DotNetNuke.Entities.Tabs.TabInfo> tabsWithModule = TabCtrl.GetTabsByPackageID(portalID, PackageID, false);
            TabCollection allPortalTabs = TabCtrl.GetTabsByPortal(PortalId);
            IDictionary<int, DotNetNuke.Entities.Tabs.TabInfo> tabsInOrder = new Dictionary<int, DotNetNuke.Entities.Tabs.TabInfo>();
            foreach (DotNetNuke.Entities.Tabs.TabInfo tab in allPortalTabs.Values)
            {
                AddChildTabsToList(tab, ref allPortalTabs, ref tabsWithModule, ref tabsInOrder);
            }
            return tabsInOrder;
        }
        private void AddChildTabsToList(DotNetNuke.Entities.Tabs.TabInfo currentTab, ref TabCollection allPortalTabs, ref IDictionary<int, DotNetNuke.Entities.Tabs.TabInfo> tabsWithModule, ref IDictionary<int, DotNetNuke.Entities.Tabs.TabInfo> tabsInOrder)
        {
            if ((tabsWithModule.ContainsKey(currentTab.TabID) && !tabsInOrder.ContainsKey(currentTab.TabID)))
            {
                tabsInOrder.Add(currentTab.TabID, currentTab);
                foreach (DotNetNuke.Entities.Tabs.TabInfo tab in allPortalTabs.WithParentId(currentTab.TabID))
                {
                    AddChildTabsToList(tab, ref allPortalTabs, ref tabsWithModule, ref tabsInOrder);
                }
            }
        }
    }
}